// log4js.js


const log4js = require("log4js");
let logger = {}

const formatError = (ctx, err) => {
    const {method,url} = ctx
    let body = ctx.request.body
    const user = ctx.state.user
    return {method, url,body,user, err}
}

const formatRes = (ctx,costTime) => {
    const {method,url,response:{status,message,body:{success}},request:{header:{authorization}}} = ctx
    let body = ctx.request.body
    const user = ctx.state.user
    return {method, url,user, body, costTime,authorization, response:{status,message,body:{success}}}
}


let errorLogger = log4js.getLogger('error')
let resLogger = log4js.getLogger('response')

// 封装错误日志
logger.errLogger = (ctx, error) => {
    if(ctx && error) {
        errorLogger.error(formatError(ctx, error))
    }
}

// 封装响应日志
logger.resLogger = (ctx, resTime) => {
    if(ctx) {
        resLogger.info(formatRes(ctx, resTime))
    }
}
module.exports = logger

